package dictdatalogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpDictDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpDictDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpDictDataLogic {
	return &UpDictDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpDictDataLogic) UpDictData(in *syspb.UpDictDataReq) (*syspb.UpDictDataResp, error) {
	dictData := in.GetParams()
	if dictData == nil || dictData.GetDictCode() == 0 || dictData.GetDictLabel() == "" || dictData.GetDictValue() == "" ||
		dictData.GetDictType() == "" || dictData.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新字典数据失败：参数缺失"),
			tool.GetErrMsgFormat("update dictData"), "params is not existed", in)
	}

	// 转换数据
	one, err := l.svcCtx.SysDictDataModel.FindOne(l.ctx, dictData.GetDictCode())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update dictData"), err, in)
	}
	one.DictSort = dictData.GetDictSort()
	one.DictLabel = dictData.GetDictLabel()
	one.DictValue = dictData.GetDictValue()
	one.DictType = dictData.GetDictType()
	one.IsDefault = dictData.GetIsDefault()
	one.Status = dictData.GetStatus()
	one.Remark = dictData.GetRemark()
	one.UpdateUser = dictData.GetUpdateUser()

	// 更新
	err = l.svcCtx.SysDictDataModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update dictData"), err, in)
	}

	return &syspb.UpDictDataResp{}, nil
}
